// DOM元素
const messageAlert = document.getElementById('messageAlert');
const userId = document.getElementById('userId');
const userUsername = document.getElementById('userUsername');
const userPhone = document.getElementById('userPhone');
const userEmail = document.getElementById('userEmail');
const userToken = document.getElementById('userToken');
const logoutBtn = document.getElementById('logoutBtn');

// 显示消息提示
function showMessage(message, type = 'info') {
    messageAlert.textContent = message;
    messageAlert.className = `message-alert ${type}`;
    messageAlert.style.display = 'block';
    
    setTimeout(() => {
        messageAlert.style.display = 'none';
    }, 3000);
}

// 检查登录状态
async function checkLoginStatus() {
    const token = localStorage.getItem('token');
    if (!token) {
        showMessage('请先登录', 'error');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1500);
        return false;
    }
    return true;
}

// 获取用户信息
async function getUserInfo() {
    try {
        const token = localStorage.getItem('token');
        const response = await fetch('/api/auth/user-info', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const user = await response.json();
            updateUserInfo(user);
        } else if (response.status === 401) {
            showMessage('登录已过期，请重新登录', 'error');
            setTimeout(() => {
                window.location.href = 'index.html';
            }, 1500);
        } else {
            showMessage('获取用户信息失败', 'error');
        }
    } catch (error) {
        showMessage('获取用户信息失败，请稍后重试', 'error');
    }
}

// 更新用户信息显示
function updateUserInfo(user) {
    userId.textContent = user.id;
    userUsername.textContent = user.username;
    userPhone.textContent = user.phone;
    userEmail.textContent = user.email || '未设置';
    userToken.textContent = localStorage.getItem('token');
}

// 退出登录
logoutBtn.addEventListener('click', () => {
    localStorage.removeItem('token');
    showMessage('已退出登录', 'info');
    setTimeout(() => {
        window.location.href = 'index.html';
    }, 1500);
});

// 页面加载时检查登录状态并获取用户信息
document.addEventListener('DOMContentLoaded', async () => {
    const isLoggedIn = await checkLoginStatus();
    if (isLoggedIn) {
        await getUserInfo();
    }
}); 